Visual Basic 2003: Code  

Code: Creating a Key In the Registry (Visual Basic)

This example adds the value pair, "Name" and "Smith", to the current user's registry, under the key "Names".

Example

Dim key As Microsoft.Win32.RegistryKey
key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("Names")
key.SetValue("Name", "Smith")

Compiling the Code

Replace the "Names" parameter with the name of a key that exists directly under the HKEY_CURRENT_USER node of the registry.

Replace the "Name" parameter with the name of a value that exists directly under the "Names" node.

Robust Programming

Examine the registry structure to find a suitable location for your key. For example, you may want to open the Software key of the current user, and create a key with your company's name. Then add the registry values to your company's key.

When reading the registry from a Web application, the current user depends on the authentication and impersonation implemented in the Web application. To determine the current user in a Web application, see Code: Getting the User or Account Identity (Visual Basic).

The following conditions may cause an exception:

Security

It is more secure to write data to the user folder (Microsoft.Win32.Registry.CurrentUser) rather than to the local computer (Microsoft.Win32.Registry.LocalMachine).

When you create a registry value, you need to decide what to do if that value already exists. Another process, perhaps a malicious one, may have already created the value and have access to it. When you put data in the registry value, the data is available to the other process. To prevent this, use the RegistryKey.GetValue method. It returns Nothing if the key does not already exist.

It is not secure to store secrets, such as passwords, in the registry as plain text, even if the registry key is protected by ACLs (see Access Control).

See Also

Code: Deleting a Key from the Registry (Visual Basic) | Code: Reading Data from the Registry (Visual Basic) | Registry Class | RegistryKey Class | Code Access Security Basics | Visual Basic Code Example Topics